import { service, updateData, addData } from '@vimi/utils-api'
import { dateFormat } from '@vimi/utils-tool'

export const getRecordData = (processItem, approveConfig, user) => {
  let { workflow_record: record, ...process } = processItem
  if (!record) {
    record = [] // null
  }

  const { cmpt = 'approve-common', rekey, dataParse } = approveConfig[process.wfn_key] || {}

  process.is_one_approval = +(process.is_one_approval || 1)
  record.forEach(r => {
    const status = +(r.approval_status || '')
    const editable = status === 0 && r.task_id && user.userId === r.wf_approval_user_id
    const date = r.approval_time || (editable ? new Date() : '')
    r.approval_status = status
    r.editable = editable
    r.dateStr = dateFormat(date, 'yyyy年MM月dd日')
  })
  const editable = record.some(it => it.editable)
  const status = Math.max(0, ...record.map(it => it.approval_status))
  const show = status > 0 || editable

  const data = {
    cmpt,
    rekey,
    editable,
    status,
    show,
    label: process.wfn_name,
    process,
    record,
  }
  return {
    ...data,
    data: dataParse ? dataParse(data) : {},
  }
}

// 获取审批流程配置信息
export const getApprove = ({ wfKey, queryId, config, next }, user) =>
  service
    .get('/api/credit/wf/', {
      params: {
        wfKey,
        wfRelatedId: queryId,
      },
    })
    .then(res => {
      const process = res?.data || []
      const approve = []
      for (const processItem of process) {
        if (next && next(processItem) === false) {
          continue
        }
        approve.push(getRecordData(processItem, config, user))
      }
      return approve
    })

// 审批
export const addApprove = (relatedId, { opinion, status, process, taskId, rekey }, user) =>
  addData({
    table: 'workflow_record',
    data: {
      approval_option: opinion,
      approval_status: status,
      approval_time: dateFormat(new Date()),
      approval_person: user.realName,
      wf_related_id: relatedId,
      task_id: taskId,
      wfn_key: process.wfn_key,
      wfn_name: process.wfn_name,
      workflow_key: process.workflow_key,
      back_wfn_key: rekey,
    },
  })

// 更新审批
export const updateApprove = (id, { opinion, status, process, taskId, rekey }, user) =>
  updateData({
    table: 'workflow_record',
    id,
    data: {
      approval_option: opinion,
      approval_status: status,
      approval_time: dateFormat(new Date()),
      approval_person: user.realName,
      task_id: taskId,
      wfn_key: process.wfn_key,
      wfn_name: process.wfn_name,
      workflow_key: process.workflow_key,
      back_wfn_key: rekey,
    },
  })

// 获取流程配置信息
export const getWfView = ({ wfKey }) =>
  service
    .get('/api/credit/wf/view/', {
      params: {
        wfKey,
      },
    })
    .then(res => {
      return res?.data || []
    })
